package Timer;
public class MyBlockingQueue {
    private String[] str;
    Object object=new Object();
    private int head;
    private int tail;
    private int capacity;
    public MyBlockingQueue(int n){
        str=new String[n];
    }
    public void put(String s) throws InterruptedException {
        synchronized (this){
            if(capacity==str.length){
                this.wait();
            }
            str[tail]=s;
            capacity++;
            tail=(tail+1)%str.length;
            notifyAll();
        }
    }
    public String take() throws InterruptedException {
        synchronized (this){
            if(capacity==0){
                this.wait();
            }
            String string=str[head];
            capacity--;
            head=(head+1)%str.length;
            notifyAll();
            return string;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue=new MyBlockingQueue(5);
        Thread t1=new Thread(()->{
            int num=0;
            while (true){
                try {
                    String s1=new String(String.valueOf(num));
                    System.out.println("生产元素："+num);
                    queue.put(s1);
                    num++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2=new Thread(()->{
            while (true){
                try {
                    String s2=queue.take();
                    System.out.println("消耗元素："+s2);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}
